package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.Account;
import cn.wolfcode.p2p.base.domain.IpLog;
import cn.wolfcode.p2p.base.domain.LoginInfo;
import cn.wolfcode.p2p.base.domain.UserInfo;
import cn.wolfcode.p2p.base.exception.CustomerException;
import cn.wolfcode.p2p.base.mapper.AccountMapper;
import cn.wolfcode.p2p.base.mapper.IpLogMapper;
import cn.wolfcode.p2p.base.mapper.LoginInfoMapper;
import cn.wolfcode.p2p.base.mapper.UserInfoMapper;
import cn.wolfcode.p2p.base.service.ILoginInfoService;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.AssertUtil;
import cn.wolfcode.p2p.base.util.Constant;
import cn.wolfcode.p2p.base.util.MD5;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class LoginInfoServiceImpl implements ILoginInfoService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private IVerifyCodeService verifyCodeService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private IpLogMapper ipLogMapper;

    @Override
    public void register(String username, String password, String verifyCode) {
        // 1.后端校验:断言
        AssertUtil.INSTANCE.isNotEmpty(username, "手机号码不能为空")
                .isNotEmpty(verifyCode, "验证码不能为空")
                .isPhoneNumber(username, "手机号格式错误,请修正!!!")
                .lengthIn(password, 4, 16, "密码在4到16位")
                .isFalse(this.checkUsernameExist(username), "亲,该账号已经存在")
        ;
        // 3.手机验证码校验
        verifyCodeService.validate(username, verifyCode);
        //-----------------------------------------------------------
        // 4.对数据进行封装
        // 把数据封装到LoginInfo对象中,并保存到数据库
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(username)
                .setPassword(MD5.encode(password))
                .setState(LoginInfo.STATE_NORMAL)
                .setUserType(LoginInfo.TYPE_USER)
        ;
        loginInfoMapper.insert(loginInfo);
        // 5.创建当前用户的基本信息,设置相关数据并保存
        UserInfo userInfo = new UserInfo();
        userInfo.setId(loginInfo.getId());
        userInfo.setPhoneNumber(loginInfo.getUsername());
        userInfoMapper.insert(userInfo);
        // 6.创建当前用户的账户信息,设置相关数据并保存
        Account account = new Account();
        account.setId(loginInfo.getId());
        account.setTradePassword(loginInfo.getPassword());
        accountMapper.insert(account);
    }

    @Override
    public void register2(LoginInfo loginInfo, String verifyCode) {
        AssertUtil.INSTANCE.isPhoneNumber(loginInfo.getUsername(), "手机号码格式错误");
        loginInfo.setPassword(MD5.encode(loginInfo.getPassword()))
                .setState(LoginInfo.STATE_NORMAL);
    }

    @Override
    public boolean checkUsernameExist(String username) {
        int row = loginInfoMapper.selectByUsername(username);
        return row > 0;
    }

    @Override
    public LoginInfo login(String username, String password, Integer userType) {
        // 1.根据账号和密码查询用户对象
        String encodePwd = MD5.encode(password);
        LoginInfo currentUser = loginInfoMapper.selectByUsernameAndPassword(username, encodePwd, userType);
        // 2.账号是否为空
//        AssertUtil.INSTANCE.isNotNull(currentUser, "账号或密码错误");
        // 3.账号是否被锁定
//        if (currentUser.getState() == LoginInfo.STATIC_LOCK) {
//            throw new CustomerException("亲,账号被锁定,请联系客服");
//        }
        // 4.将当前登录信息存到HttpSession中
        if (currentUser != null) {
            UserContext.setCurrentUser(currentUser);
        }
        // 登录日志
        IpLog ipLog = new IpLog().setUsername(username)
                .setLoginTime(new Date())
                .setIp(UserContext.getCurrentUserIp())
                .setState(currentUser != null ? IpLog.STATE_SUCCESS : IpLog.STATE_FAILED)
                .setUserType(userType);
        // 根据前端用户类型,存储当前日志的user_type类型
        ipLogMapper.insert(ipLog);
        return currentUser;
    }

    @Override
    public void initAdmin() {
        // 1.判断管理员数量,为0则增加一个管理员,否则不操作
        int rows = loginInfoMapper.selectByUserType(LoginInfo.TYPE_MANAGER);
        if (rows == 0) {
            LoginInfo admin = new LoginInfo()
                    .setUsername(Constant.DEFAULT_ADMIN_USERNAME)
                    .setPassword(MD5.encode(Constant.DEFAULT_ADMIN_PASSWORD))
                    .setState(LoginInfo.STATE_NORMAL)
                    .setUserType(LoginInfo.TYPE_MANAGER);
            loginInfoMapper.insert(admin);
        }
    }

    @Override
    public List<LoginInfo> getCustomeServices() {
        return loginInfoMapper.selectCustomeServices();
    }
}
